package com.zlf.sb.demo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;

/***
 *@title ExternalSort
 *@description <TODO description class purpose>
 *@author wgc_j
 *@version 1.0.0
 *@create 2025-02-13 16:50
 **/
public class ExternalSort {
    public static final int CHUNK_SIZE = 100;

    public static void main(String[] args) throws Exception {
        int size = 100000000; // 一亿个数字
        FileWriter file = new FileWriter("D:\\input.txt");
        Random random = new Random();
        try (BufferedWriter writer = new BufferedWriter(file)) {
            for (int i = 0; i < size; i++) {
                // 生成随机数字，范围可以根据需要调整
                int number = random.nextInt(1000000000); // 生成0到999999999之间的随机数
                // 将数字转换为字符串，并写入文件，每行一个数字
                writer.write(String.valueOf(number));
                writer.newLine();
            }
            System.out.println("数字已成功写入文件。");
        } catch (IOException e) {
            System.err.println("写入文件时发生错误: " + e.getMessage());
        }
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(Collections.reverseOrder());
        Scanner scanner = new Scanner(new File("D:\\input.txt"));
        while (scanner.hasNextInt()) {
            List<Integer> chunk = new ArrayList<Integer>();
            for (int i = 0; i < CHUNK_SIZE && scanner.hasNextInt(); i++) {
                chunk.add(scanner.nextInt());
            }
            // 在内存中对当前块排序并更新最大值堆
            Collections.sort(chunk, Collections.reverseOrder());
            for (int num : chunk) {
                if (minHeap.size() < 100) {
                    minHeap.offer(num);
                } else if (num > minHeap.peek()) {
                    minHeap.poll();
                    minHeap.offer(num);
                }
            }

        }
        scanner.close();
        PrintWriter writer = new PrintWriter(new File("D:\\output.txt"), "UTF-8");
        while (!minHeap.isEmpty()) {
            writer.println(minHeap.poll());
        }
        writer.close();
    }
}
